package com.lbc.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;

@Controller
public class IndexController {

    @Autowired
    private Redisson redisson;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/deduct_stock")
    public String deductStock() {
        String lockKey = "product_001";

        String client = UUID.randomUUID().toString();

        RLock redissonLock = redisson.getLock(lockKey);
        try {
//            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "lbc");  //  jedis.setnx(key,value);
//            stringRedisTemplate.expire(lockKey, 10, TimeUnit.SECONDS);
//            Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, client, 10, TimeUnit.SECONDS);
//            if (!result) {
//                return "error_code";
//            }
            redissonLock.lock();  //  .setIfAbsent(lockKey, client, 10, TimeUnit.SECONDS);
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));  //  jedis.get("stock")
            if (stock > 0) {
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("stock", realStock+"");
                System.out.println("扣减成功，剩余库存：" + realStock);  //  jedis.set(key,value);
            } else {
                System.out.println("扣减失败，库存不足");
            }
        } finally {
            redissonLock.unlock();
//            if (client.equals(stringRedisTemplate.opsForValue().get(lockKey)) {
//                stringRedisTemplate.delete(lockKey);
//            }
        }
        return "end";
    }
}
